package com.zenithmind.chat.controller;

import com.zenithmind.chat.pojo.dto.ChatGroupDTO;
import com.zenithmind.chat.pojo.query.ChatGroupQuery;
import com.zenithmind.chat.pojo.vo.ChatGroupVO;
import com.zenithmind.chat.pojo.vo.ChatUserVO;
import com.zenithmind.chat.service.ChatGroupService;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 聊天群组控制器
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@RestController
@RequestMapping("/api/zenithMind/chat/group")
@RequiredArgsConstructor
@Tag(name = "聊天群组管理", description = "聊天群组相关接口")
public class ChatGroupController {

    private final ChatGroupService groupService;

    @GetMapping("/page")
    @Operation(summary = "分页查询群组列表", description = "支持多条件查询群组")
    public Result<PageResult<ChatGroupVO>> getGroupPage(@Validated ChatGroupQuery query) {
        PageResult<ChatGroupVO> result = groupService.getGroupPage(query);
        return Result.success(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取群组详情", description = "根据ID获取群组详细信息")
    public Result<ChatGroupVO> getGroupById(
            @Parameter(description = "群组ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        ChatGroupVO group = groupService.getGroupById(id, userId);
        return Result.success(group);
    }

    @PostMapping
    @Operation(summary = "创建群组", description = "创建新的聊天群组")
    public Result<String> createGroup(@Validated @RequestBody ChatGroupDTO groupDTO) {
        String userId = UserContext.getUserId();
        String groupId = groupService.createGroup(groupDTO, userId);
        return Result.success(groupId);
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新群组信息", description = "更新群组基本信息")
    public Result<Boolean> updateGroup(
            @Parameter(description = "群组ID") @PathVariable String id,
            @Validated @RequestBody ChatGroupDTO groupDTO) {
        String userId = UserContext.getUserId();
        Boolean result = groupService.updateGroup(id, groupDTO, userId);
        return Result.success(result);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除群组", description = "删除指定群组")
    public Result<Boolean> deleteGroup(
            @Parameter(description = "群组ID") @PathVariable String id) {
        String userId = UserContext.getUserId();
        Boolean result = groupService.deleteGroup(id, userId);
        return Result.success(result);
    }

    @DeleteMapping("/batch")
    @Operation(summary = "批量删除群组", description = "批量删除多个群组")
    public Result<Boolean> deleteGroupsBatch(@RequestBody List<String> ids) {
        String userId = UserContext.getUserId();
        Boolean result = groupService.deleteGroupsBatch(ids, userId);
        return Result.success(result);
    }

    @GetMapping("/user")
    @Operation(summary = "获取用户群组列表", description = "获取当前用户加入的群组")
    public Result<List<ChatGroupVO>> getUserGroups(
            @Parameter(description = "成员状态") @RequestParam(required = false) Integer status) {
        String userId = UserContext.getUserId();
        List<ChatGroupVO> groups = groupService.getUserGroups(userId, status);
        return Result.success(groups);
    }

    @GetMapping("/public")
    @Operation(summary = "获取公开群组列表", description = "获取所有公开的群组")
    public Result<List<ChatGroupVO>> getPublicGroups(@Validated ChatGroupQuery query) {
        List<ChatGroupVO> groups = groupService.getPublicGroups(query);
        return Result.success(groups);
    }

    @PostMapping("/{id}/join")
    @Operation(summary = "加入群组", description = "申请加入指定群组")
    public Result<Boolean> joinGroup(
            @Parameter(description = "群组ID") @PathVariable String id,
            @Parameter(description = "邀请人ID") @RequestParam(required = false) String inviterId) {
        String userId = UserContext.getUserId();
        Boolean result = groupService.joinGroup(id, userId, inviterId);
        return Result.success(result);
    }

    @PostMapping("/{id}/leave")
    @Operation(summary = "退出群组", description = "退出指定群组")
    public Result<Boolean> leaveGroup(
            @Parameter(description = "群组ID") @PathVariable String id,
            @Parameter(description = "退出原因") @RequestParam(required = false) String reason) {
        String userId = UserContext.getUserId();
        Boolean result = groupService.leaveGroup(id, userId, reason);
        return Result.success(result);
    }

    @PostMapping("/{id}/invite")
    @Operation(summary = "邀请用户", description = "邀请用户加入群组")
    public Result<Boolean> inviteUsers(
            @Parameter(description = "群组ID") @PathVariable String id,
            @RequestBody List<String> userIds) {
        String userId = UserContext.getUserId();
        Boolean result = groupService.inviteUsers(id, userIds, userId);
        return Result.success(result);
    }

    @PostMapping("/{id}/remove")
    @Operation(summary = "移除成员", description = "从群组中移除成员")
    public Result<Boolean> removeMembers(
            @Parameter(description = "群组ID") @PathVariable String id,
            @RequestBody List<String> userIds,
            @Parameter(description = "移除原因") @RequestParam(required = false) String reason) {
        String userId = UserContext.getUserId();
        Boolean result = groupService.removeMembers(id, userIds, userId, reason);
        return Result.success(result);
    }

    @PostMapping("/{id}/admin/set")
    @Operation(summary = "设置管理员", description = "设置群组管理员")
    public Result<Boolean> setAdmins(
            @Parameter(description = "群组ID") @PathVariable String id,
            @RequestBody List<String> userIds) {
        String userId = UserContext.getUserId();
        Boolean result = groupService.setAdmins(id, userIds, userId);
        return Result.success(result);
    }

    @PostMapping("/{id}/admin/remove")
    @Operation(summary = "取消管理员", description = "取消群组管理员权限")
    public Result<Boolean> removeAdmins(
            @Parameter(description = "群组ID") @PathVariable String id,
            @RequestBody List<String> userIds) {
        String userId = UserContext.getUserId();
        Boolean result = groupService.removeAdmins(id, userIds, userId);
        return Result.success(result);
    }

    @PostMapping("/{id}/mute")
    @Operation(summary = "禁言成员", description = "禁言群组成员")
    public Result<Boolean> muteMembers(
            @Parameter(description = "群组ID") @PathVariable String id,
            @RequestBody List<String> userIds,
            @Parameter(description = "禁言时长(分钟)") @RequestParam Integer muteMinutes) {
        String userId = UserContext.getUserId();
        Boolean result = groupService.muteMembers(id, userIds, muteMinutes, userId);
        return Result.success(result);
    }

    @PostMapping("/{id}/unmute")
    @Operation(summary = "解除禁言", description = "解除群组成员禁言")
    public Result<Boolean> unmuteMembers(
            @Parameter(description = "群组ID") @PathVariable String id,
            @RequestBody List<String> userIds) {
        String userId = UserContext.getUserId();
        Boolean result = groupService.unmuteMembers(id, userIds, userId);
        return Result.success(result);
    }

    @PostMapping("/{id}/transfer")
    @Operation(summary = "转让群主", description = "转让群主权限")
    public Result<Boolean> transferOwnership(
            @Parameter(description = "群组ID") @PathVariable String id,
            @Parameter(description = "新群主ID") @RequestParam String newOwnerId) {
        String userId = UserContext.getUserId();
        Boolean result = groupService.transferOwnership(id, newOwnerId, userId);
        return Result.success(result);
    }

    @PutMapping("/{id}/announcement")
    @Operation(summary = "更新群公告", description = "更新群组公告")
    public Result<Boolean> updateAnnouncement(
            @Parameter(description = "群组ID") @PathVariable String id,
            @Parameter(description = "公告内容") @RequestParam String announcement) {
        String userId = UserContext.getUserId();
        Boolean result = groupService.updateAnnouncement(id, announcement, userId);
        return Result.success(result);
    }

    @GetMapping("/{id}/members")
    @Operation(summary = "获取群组成员", description = "分页获取群组成员列表")
    public Result<PageResult<ChatUserVO>> getGroupMembers(
            @Parameter(description = "群组ID") @PathVariable String id,
            @Parameter(description = "成员状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "成员角色") @RequestParam(required = false) Integer role,
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "20") Integer pageSize) {
        PageResult<ChatUserVO> result = groupService.getGroupMembers(id, status, role, keyword, pageNum, pageSize);
        return Result.success(result);
    }

    @PostMapping("/course")
    @Operation(summary = "创建课程群", description = "为课程创建专属群组")
    public Result<String> createCourseGroup(
            @Parameter(description = "课程ID") @RequestParam String courseId,
            @Parameter(description = "课程名称") @RequestParam String courseName) {
        String userId = UserContext.getUserId();
        String groupId = groupService.createCourseGroup(courseId, courseName, userId);
        return Result.success(groupId);
    }

    @PostMapping("/project")
    @Operation(summary = "创建项目群", description = "为项目创建专属群组")
    public Result<String> createProjectGroup(
            @Parameter(description = "项目ID") @RequestParam String projectId,
            @Parameter(description = "项目名称") @RequestParam String projectName) {
        String userId = UserContext.getUserId();
        String groupId = groupService.createProjectGroup(projectId, projectName, userId);
        return Result.success(groupId);
    }

    @GetMapping("/statistics")
    @Operation(summary = "获取群组统计", description = "获取群组统计信息")
    public Result<Object> getGroupStatistics() {
        Object statistics = groupService.getGroupStatistics();
        return Result.success(statistics);
    }

    @PutMapping("/{id}/status")
    @Operation(summary = "更新群组状态", description = "启用或禁用群组")
    public Result<Boolean> updateGroupStatus(
            @Parameter(description = "群组ID") @PathVariable String id,
            @Parameter(description = "状态") @RequestParam Integer status) {
        String userId = UserContext.getUserId();
        Boolean result = groupService.updateGroupStatus(id, status, userId);
        return Result.success(result);
    }
}
